import { promises } from "fs";
import fsextra from "fs-extra";
import path from "path";
import { StateType } from "../src/StateType";
import { __dirname } from "./index";

export async function savestates(states: StateType) {
    const statespath = path.resolve(__dirname, "../temp/states.js");
    const { menulist, catalogue } = states;

    const serilizedtext = [
        `export const menulist=${JSON.stringify(Array.from(menulist))}`,
        `export const catalogue=${JSON.stringify(Array.from(catalogue))}`,
        `export const loadpagedatamap={${menulist
            .map((url) => {
                return (
                    JSON.stringify(url) +
                    ":" +
                    "()=>import(" +
                    JSON.stringify("~/temp/page/" + btoa(url) + ".js") +
                    ")"
                );
            })
            .join(",\n")}}`,
    ].join("\n");

    await fsextra.ensureFile(statespath);
    await promises.writeFile(statespath, serilizedtext);
}
